#!/bin/sh

APP_NAME="xyz"
APP_DIR=`dirname $0`
APP_DIR=`cd "$APP_DIR"\; pwd`
BIN="${APP_DIR}/${APP_NAME}"

if [ -z "${XDG_DATA_DIRS}" ] \; then
    XDG_DATA_DIRS="${APP_DIR}/share/:${HOME}/.local/share/:/usr/local/share/:/usr/share/"
else
    XDG_DATA_DIRS="${APP_DIR}/share/:${XDG_DATA_DIRS}"
fi

if [ -z "${PATH}" ] \; then # ??
    PATH="${APP_DIR}"
else	
    PATH="${APP_DIR}:${PATH}"
fi
export APP_DIR
export PATH
export XDG_DATA_DIRS

case $1 in
    --compile)
	own=0 # own window not necessary for 0compile
	if [ "a${BUILDDIR}" = "a" ]\; then
	    BUILDDIR="${APP_DIR}/build"
	    export BUILDDIR
	    own=1
	fi
	if [ "a${SRCDIR}" = "a" ]\; then
	    SRCDIR="${APP_DIR}/src"
	    export SRCDIR
	    own=1
	else
	    #ugly workarounds because cmake don't like the zero install filenames...
	    SRCDIR="${SRCDIR}/src"
	    tmp=`mktemp -d /tmp/source.XXXXXXXXXX`
	    if [ $? -ne 0 ] \; then
		echo "Couldn't create temporary file!" >&2
		exit 1
	    fi
	    tmp="${tmp}/src"
	    if ! ln -s "$SRCDIR" "$tmp" \; then
		echo "Couldn't link source dir!" >&2
		exit 1
	    fi
	    SRCDIR="$tmp"
	    export SRCDIR
	fi
	if [ "a${DISTDIR}" = "a" ]\; then
	    DISTDIR="${APP_DIR}"
	    export DISTDIR
	    own=1
	fi
	if [ $own -eq 1 ]\; then
	    DO_READ_WAIT="ok"
	    export DO_READ_WAIT
	    xterm=`sed -n -e 's/.*<option\sname=\"menu_xterm\">\(.*\)<\/option>.*/\1/ip'  ~/.config/rox.sourceforge.net/ROX-Filer/Options`
	    if [ ${#xterm} -gt 0 ] \; then
		if which "$xterm" >/dev/null 2>&1 \; then
		    exec "$xterm" -e "${APP_DIR}/compile.sh"
		fi
	    fi
  	    if [ -x "/etc/alternatives/x-terminal-emulator" ] \; then
		exec /etc/alternatives/x-terminal-emulator -e "${APP_DIR}/compile.sh"
	    else
     		exec xterm -e  "${APP_DIR}/compile.sh"
	    fi
	else
	    exec ${APP_DIR}/compile.sh
	fi
esac


if [ -x "$BIN" ]\; then
    exec $BIN "$@"
else
    if [ "a${BUILDDIR}" = "a" ]\; then
	BUILDDIR="${APP_DIR}/build"
	own=1
    fi
    export BUILDDIR
    if [ "a${SRCDIR}" = "a" ]\; then
	SRCDIR="${APP_DIR}/src"
	own=1
    fi
    export SRCDIR
    if [ "a${DISTDIR}" = "a" ]\; then
	DISTDIR="${APP_DIR}"
	own=1
    fi
    export DISTDIR

    echo "ERROR from $0:" >&2
    echo "I cannot find an executable file" >&2
    echo "Trying to compile..." >&2
    if [ -n "$DISPLAY" ]\; then
        xterm=`sed -n -e 's/.*<option\sname=\"menu_xterm\">\(.*\)<\/option>.*/\1/ip'  ~/.config/rox.sourceforge.net/ROX-Filer/Options`
	ok=1
	if [ ${#xterm} -gt 0 ] \; then
	    if which "$xterm" >/dev/null 2>&1 \; then
		"$xterm" -e "${APP_DIR}/compile.sh"
		ok=0
	    fi
	fi
  	if [ $ok -eq 1 ] \; then
	    if [ -x "/etc/alternatives/x-terminal-emulator" ] \; then
		/etc/alternatives/x-terminal-emulator -e "${APP_DIR}/compile.sh"
	    else
     		xterm -e  "${APP_DIR}/compile.sh"
	    fi
	fi
    else
	${APP_DIR}/compile.sh
    fi
    if [ -x "$BIN" ]\; then
	exec $BIN "$@"
    fi
    exit 1
fi
